// ==UserScript==
// @name         bili home black
// @namespace    http://tampermonkey.net/
// @version      2024-01-16
// @description  try to take over the world!
// @author       You
// @match        https://www.bilibili.com/
// @match        https://www.bilibili.com/?spm_id_from=*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=bilibili.com
// @grant        GM_xmlhttpRequest
// @run-at       document-end
// ==/UserScript==

(function() {
    let access_token = "you access_token here"
    let blacked_list_url = "you blacked_list_url here"

    let global_opacity = 0.25
    let global_blacked_json

    function get_blacked(){
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method:     'GET',
                url:        blacked_list_url + '?access_token=' + access_token,
                headers:    {'Content-Type': 'application/json;charset=UTF-8'},
                onload:     function (response) {
                    let blacked_response = JSON.parse(response.responseText)
                    console.log('sha：'+ blacked_response.sha)
                    global_blacked_json = JSON.parse(decodeURIComponent(escape(window.atob(blacked_response.content))))
                    //console.log('blacked_array：'+ global_blacked_json.black_list)
                    resolve(blacked_response.sha)
                },
                timeout:5000,
                ontimeout:function(){
                    console.log('ontimeout')
                    backup_get_blacked()
                },
                onerror:function(e){
                    console.log('error')
                    backup_get_blacked()
                }
            })
        });
    }

    function put_blacked(blacked_json, item, up_name, tf){
        return (async (e) => {
            console.log('put_blacked:' + up_name)
            tf?.(e)
            // 避免sha过期
            let sha = await get_blacked()
            // 添加要屏蔽的名称
            blacked_json.black_list.push(up_name)
            // 去重
            blacked_json.black_list = Array.from(new Set(blacked_json.black_list))
            // 构建请求体
            let put_content = window.btoa(unescape(encodeURIComponent(JSON.stringify(blacked_json))))
            let put_data = {
                'access_token': access_token,
                'content':put_content,
                'sha':sha,
                'message':'添加黑名单:' + up_name
            }
            GM.xmlHttpRequest({
                method:     'PUT',
                url:        blacked_list_url,
                data:       JSON.stringify(put_data),
                headers:    {'Content-Type': 'application/json;charset=UTF-8'},
                onload:     function(response) {
                    if(response.status === 200){
                        item.style.opacity = global_opacity
                        item.style['pointer-events'] = 'none'
                    }
                }
            })
        })
    }

    function simulateMouseover(target_ele){
        let mouse_event = new MouseEvent('mouseenter', {
            bubbles: true,
        });
        target_ele.dispatchEvent(mouse_event)
    }

    let blacking_rcmd_delay = 0
    let add_count = 0
    function blacking_feed (){
        if(blacking_rcmd_delay === 0){
            blacking_rcmd_delay = 1
            let blacked_json = global_blacked_json
            console.log('blacking')
            let bili_video_card = document.getElementsByClassName('bili-video-card is-rcmd')
            console.log('bili_video_card.length',bili_video_card.length)

            for(let i = add_count ;i < bili_video_card.length; i++) {
                let item = bili_video_card[i]
                let info_bottom,up_name,black_button,ad_card
                try{
                    // console.log(item)
                    info_bottom = item.getElementsByClassName('bili-video-card__info--bottom')[0]
                    up_name = info_bottom.getElementsByClassName('bili-video-card__info--author')[0].innerText
                    if(item.getElementsByClassName('added_custom_title')[0] !== undefined){
                        continue
                    }
                    // disable ad
                    if(item.getElementsByClassName('bili-video-card__info--ad')[0] !== undefined){
                        ad_card = item.getElementsByClassName('bili-video-card__info--ad')[0]
                    }
                    if(item.getElementsByClassName('bili-video-card__info--creative-ad')[0] !== undefined){
                        ad_card = item.getElementsByClassName('bili-video-card__info--creative-ad')[0]
                    }
                    // hide ad card
                    if(ad_card){
                        item.style.opacity = global_opacity
                        item.style['pointer-events'] = 'none'
                        continue
                    }
                    // 不看小于3分钟的视频
                    if(item.getElementsByClassName('bili-video-card__stats__duration')[0] !== undefined){
                        if(item.getElementsByClassName('bili-video-card__stats__duration')[0]?.innerHTML.split(':').length === 2){
                            if(parseInt(item.getElementsByClassName('bili-video-card__stats__duration')[0].innerHTML) < 3 ){
                                // console.log(item.getElementsByClassName('bili-video-card__stats__duration')[0].innerHTML)
                                // console.log(parseInt(item.getElementsByClassName('bili-video-card__stats__duration')[0].innerHTML))
                                if(item.getElementsByClassName('bili-video-card__info--no-interest')[0] === undefined) continue
                                simulateMouseover(item.getElementsByClassName('bili-video-card__info--no-interest')[0])
                                let bili_video_card__info__no_interest_panel = document.getElementsByClassName('bili-video-card__info--no-interest-panel')
                                setTimeout(()=>{bili_video_card__info__no_interest_panel?.[bili_video_card__info__no_interest_panel.length - 1]?.lastElementChild?.click()},3000)
                                // put_blacked(blacked_json, item, up_name)()
                                continue
                            }
                        }
                    }

                    black_button = document.createElement('a')
                }catch(e){
                    console.log(e)
                    if(e == 'TypeError: info_bottom is undefined'){
                        continue
                    }
                    if(e == "TypeError: Cannot read properties of undefined (reading 'getElementsByClassName')"){
                        continue
                    }
                }
                black_button.setAttribute('class','bili-video-card__info--owner added_custom_title')
                black_button.style='float: right;'

                let str = document.createElement('span')
                str.style='float: right;color: #880808;'
                str.setAttribute('class','bili-video-card__info--author')
                str.innerHTML = '&nbsp;&nbsp;&nbsp;屏蔽'
                black_button.append(str)
                //console.log(info_bottom)
                info_bottom.append(black_button)

                // item.addEventListener('mouseenter',()=>{console.log('mouse enter item')})

                if (blacked_json.black_list?.includes(up_name)){
                    // item.style.visibility='hidden'
                    item.style.opacity = global_opacity
                    // item.style['pointer-events'] = 'none'
                    item.addEventListener('mouseenter',(e)=>{if(e.isTrusted) e.stopImmediatePropagation();e.preventDefault();},true)
                    item.addEventListener('click',(e)=>{e.stopImmediatePropagation();e.preventDefault();},true)
                    item.addEventListener('contextmenu',(e)=>{
                        e.preventDefault()
                        simulateMouseover(item.getElementsByClassName('bili-video-card__info--no-interest')[0])
                        let bili_video_card__info__no_interest_panel = document.getElementsByClassName('bili-video-card__info--no-interest-panel')
                        setTimeout(()=>{bili_video_card__info__no_interest_panel?.[bili_video_card__info__no_interest_panel.length - 1]?.lastElementChild?.click()},500)
                    })
                }else{
                    // 点击屏蔽
                    black_button.addEventListener('click',put_blacked(blacked_json, item, up_name))
                    // 右键屏蔽
                    item.addEventListener('contextmenu',put_blacked(blacked_json, item, up_name,(e)=>{
                        if(e.button === 2){
                            e.preventDefault()
                            simulateMouseover(item.getElementsByClassName('bili-video-card__info--no-interest')[0])
                            let bili_video_card__info__no_interest_panel = document.getElementsByClassName('bili-video-card__info--no-interest-panel')
                            setTimeout(()=>{bili_video_card__info__no_interest_panel?.[bili_video_card__info__no_interest_panel.length - 1]?.lastElementChild?.click()},500)
                        }
                    }))
                }
            }
            add_count = bili_video_card.length
            console.log('black done')
            setTimeout(function(){
                blacking_rcmd_delay = 0
            },3000)
        }
    }

    (async()=>{
        await get_blacked()
        blacking_feed()
        // document.addEventListener('mousewheel',blacking_feed)

        let blackingFeedObserver = new MutationObserver(async ()=>{
            console.log('childList change')
            blacking_rcmd_delay = 0
            add_count = 0
            await get_blacked()
            blacking_feed()
        })
        blackingFeedObserver.observe(document.getElementsByClassName('container')[0], { childList:true});

    })()
})();